import { CopyOutlined } from "@ant-design/icons"
import { Space } from "antd"
import React, { useRef } from "react"

import { Toast } from "@/components/messages"
import { useLocale } from "@/locales"

interface ICopyTextButtonProps {
	text: string
}

const CopyTextButton: React.FC<ICopyTextButtonProps> = ({ text }) => {
	const textRef = useRef(null)
	const { formatMessage } = useLocale()

	const copyToClipboard = () => {
		if (textRef.current) {
			navigator.clipboard
				.writeText(text)
				.then(() => {
					Toast.success(formatMessage({ id: "common.copied" }))
				})
				.catch(() => {
					Toast.error(formatMessage({ id: "common.copy_failed" }))
				})
		}
	}

	return (
		<Space ref={textRef} onClick={() => copyToClipboard()} style={{ cursor: "pointer" }}>
			{text}
			<CopyOutlined />
		</Space>
	)
}

export default CopyTextButton
